//
//  ImageTableViewCell.m
//  GoldBook
//
//  Created by wmz on 2021/8/20.
//  Copyright © 2021 wmz. All rights reserved.
//

#import "ImageTableViewCell.h"
#import "YBImageBrowser.h"
#import "UIButton+WebCache.h"
@interface ImageTableViewCell()<UICollectionViewDelegate,UICollectionViewDataSource,HDCollectionViewBaseFlowLayoutDelegate>
/// 图片
@property (nonatomic, strong) UICollectionView *tagCollectionView;

@end

@implementation ImageTableViewCell

- (void)hd_setupViews{
    [self.contentView addSubview:self.tagCollectionView];
    [self.contentView addSubview:self.lineView];
}

- (void)updateConstraints{
    [self.tagCollectionView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(self.model.contentInset.left);
        make.right.mas_equalTo(-self.model.contentInset.right);
        make.top.mas_equalTo(self.model.contentInset.top);
        make.height.mas_equalTo(self.tagCollectionView.collectionViewLayout.collectionViewContentSize);
        make.bottom.mas_equalTo(-self.model.contentInset.bottom);
    }];
    
    [super updateConstraints];
}

- (void)setGNModel:(GNTagViewCellModel*)data{
    self.model = data;
    if (self.model.edit) {
        BOOL result = NO;
        for (BaseCellModel *mo in  self.model.dataSource) {
            if (mo.isSelected){
                result = YES;
                break;
            }
        }
        if (!result) {
            if (!self.model.maxCount || (self.model.maxCount && self.model.dataSource.count < self.model.maxCount)) {
                BaseCellModel *model = BaseCellModel.new;
                model.select = YES;
                NSMutableArray *marr = [NSMutableArray arrayWithArray:self.model.dataSource];
                [marr insertObject:model atIndex:0];
                self.model.dataSource = [NSArray arrayWithArray:marr];
            }
        }
    }
    self.lineView.hidden = !self.model.lineHidden;
    self.model.notCacheHeight = YES;
    self.tagCollectionView.backgroundColor = data.collectionViewBgColor;
    [self.tagCollectionView reloadData];
    [self.tagCollectionView layoutIfNeeded];
    [self setNeedsUpdateConstraints];
}

#pragma mark datasource
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    BaseCellModel *model = self.model.dataSource[indexPath.row];
    if (!model.isSelected) {
        [self showIndex:indexPath.row];
    }else{
        if (!self.model.edit) return;
        NSInteger maxCount = 1;
        if (self.model.maxCount) {
            BaseCellModel *firstObject = self.model.dataSource.firstObject;
            if (firstObject.isSelected) {
                if (self.model.maxCount > (self.model.dataSource.count - 1)) {
                    maxCount = self.model.maxCount - (self.model.dataSource.count - 1);
                }
            }
        }
        
        [PostWindow.shareInstance pushImageVC:^(NSArray<UIImage *> * _Nullable image) {
            if (image.count) {
                for (UIImage *ima in image) {
                    BaseCellModel *mo = BaseCellModel.new;
                    mo.imageTitle = (NSString*)ima;
                    NSMutableArray *marr = [NSMutableArray arrayWithArray:self.model.dataSource];
                    [marr addObject:mo];
                    self.model.dataSource = [NSArray arrayWithArray:marr];
                }
                [self updateData];
                [self.tagCollectionView reloadData];
                [self.tagCollectionView layoutIfNeeded];
                [GNEvent eventResponder:self target:self key:@"reloadCell"];
            }
        } maxCount:maxCount];
    }
}

- (void)updateData{
    if (self.model.edit && self.model.maxCount) {
        BaseCellModel *firstObject = self.model.dataSource.firstObject;
        if (firstObject.isSelected) {
            if (self.model.dataSource.count >= (self.model.maxCount + 1)) {
                NSMutableArray *marr = [NSMutableArray arrayWithArray:self.model.dataSource];
                [marr removeObjectAtIndex:0];
                self.model.dataSource = [NSArray arrayWithArray:marr];
            }
        }else{
            if (self.model.dataSource.count < self.model.maxCount ) {
                BaseCellModel *model = BaseCellModel.new;
                model.select = YES;
                NSMutableArray *marr = [NSMutableArray arrayWithArray:self.model.dataSource];
                [marr insertObject:model atIndex:0];
                self.model.dataSource = [NSArray arrayWithArray:marr];
            }
        }
    }
}

- (void)showIndex:(NSInteger)index{
    NSMutableArray <YBIBImageData*>*marr = [NSMutableArray new];
    for (BaseCellModel *model in self.model.dataSource) {
        if (!model.isSelected) {
            YBIBImageData *data = [YBIBImageData new];
            if ([model.imageTitle isKindOfClass:NSString.class]) {
                data.imageURL = [NSURL URLWithString:model.imageTitle];
            } else if ([model.imageTitle isKindOfClass:UIImage.class]) {
                data.image = ^UIImage * _Nullable{
                    return (UIImage*)model.imageTitle;
                };
            }
            [marr addObject:data];
        }
    }
    YBImageBrowser *browser = [YBImageBrowser new];
    browser.dataSourceArray = marr;
    browser.autoHideProjectiveView = false;
    BaseCellModel *firstObject = self.model.dataSource.firstObject;
    if (firstObject.isSelected) {
        browser.currentPage = index - 1;
    }else{
        browser.currentPage = index;
    }
    [browser show];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    GNTagCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"GNTagCollectionViewCell" forIndexPath:indexPath];
    cell.nameLb.clipsToBounds = YES;
    cell.nameLb.layer.cornerRadius = 8;
    cell.nameLb.userInteractionEnabled = NO;
    BaseCellModel *model = self.model.dataSource[indexPath.row];
    if (self.model.edit) {
        cell.deleteBTN.hidden = model.isSelected;
    }else{
        cell.deleteBTN.hidden = YES;
    }
    @HDWeakify(self)
    cell.deleteBTN.add_event(^(UIView * _Nonnull sender) {
        @HDStrongify(self)
        NSMutableArray *marr = [NSMutableArray arrayWithArray:self.model.dataSource];
        if (marr.count > indexPath.row) {
            [marr removeObjectAtIndex:indexPath.row];
        }
        self.model.dataSource = [NSArray arrayWithArray:marr];
        [self updateData];
        [self.tagCollectionView reloadData];
        [GNEvent eventResponder:self target:self key:@"reloadCell"];
    });
    if (model.isSelected) {
        cell.nameLb.add_image([UIImage imageNamed:@"common_upload"]);
    }else{
        if ([model.imageTitle isKindOfClass:NSString.class]) {
            [cell.nameLb sd_setImageWithURL:[NSURL URLWithString:model.imageTitle] forState:UIControlStateNormal placeholderImage:nil  completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
                if (!error) model.imageTitle = (NSString*)image;
            }];
        } else if ([model.imageTitle isKindOfClass:UIImage.class]) {
            cell.nameLb.add_image((UIImage*)model.imageTitle);
        }
    }
    cell.nameLb.imageView.contentMode = UIViewContentModeScaleToFill;
    cell.nameLb.imageView.frame = cell.nameLb.bounds;
    return cell;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.model.dataSource.count;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return self.model.itemSize;
}

- (UICollectionView *)tagCollectionView{
    if (!_tagCollectionView) {
        HDCollectionViewVerticalLayout *flowLayout = [[HDCollectionViewVerticalLayout alloc] init];
        flowLayout.delegate = self;
        _tagCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, PostWidth - 20, PostNum(28)) collectionViewLayout:flowLayout];
        _tagCollectionView.delegate = self;
        _tagCollectionView.dataSource = self;
        _tagCollectionView.scrollEnabled = NO;
        [_tagCollectionView registerClass:GNTagCollectionViewCell.class forCellWithReuseIdentifier:@"GNTagCollectionViewCell"];
    }
    return _tagCollectionView;
}

@end
